package com.xiangxiao.rpan.file.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2022/12/29 10:26
 */
@Configuration
@Primary
public class DataSourceConfig {
  // private Logger log = LoggerFactory.getLogger(DataSourceConfig.class);

  @Value("${spring.datasource.url}")
  //jdbc:mysql://127.0.0.1:3306/insight?useUnicode=true&characterEncoding=utf8&failOverReadOnly=false&allowMultiQueries=true
  private String datasourceUrl;
  @Value("${spring.datasource.driver-class-name}")
  private String driverClassName;
  @Value("${spring.datasource.username}")
  private String username;
  @Value("${spring.datasource.password}")
  private String password;
  @Value("${spring.datasource.druid.max-active}")
  private int maxActive;
  @Value("${spring.datasource.druid.initial-size}")
  private int initialSize;
  @Value("${spring.datasource.druid.min-idle}")
  private int minIdle;
  @Value("${spring.datasource.druid.max-wait-millis}")
  private int maxWait;

  @Bean     //声明其为Bean实例
  public DataSource dataSource() {
    DruidDataSource datasource = new DruidDataSource();

    datasource.setUrl(datasourceUrl);
    datasource.setUsername(username);
    datasource.setPassword(password);
    datasource.setDriverClassName(driverClassName);
    datasource.setMaxActive(maxActive);
    datasource.setInitialSize(initialSize);
    datasource.setMinIdle(minIdle);
    datasource.setMaxWait(maxWait);

    try {
      Class.forName(driverClassName);

      String url01 = datasourceUrl.substring(0, datasourceUrl.indexOf("?"));

      String url02 = url01.substring(0, url01.lastIndexOf("/"));

      String datasourceName = url01.substring(url01.lastIndexOf("/") + 1);
      // 连接已经存在的数据库，如：mysql
      Connection connection = DriverManager.getConnection(url02, username, password);
      Statement statement = connection.createStatement();

      // 创建数据库
      statement.executeUpdate("create database if not exists `" + datasourceName + "` default character set utf8 COLLATE utf8_general_ci");

      statement.close();
      connection.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

    return datasource;
  }

}
